<?php
declare(strict_types=1);

namespace Modules\Base\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Modules\Base\Models\Material;
use Illuminate\Http\Request;


class MaterialController extends Controller
{
    public function __construct(
        protected readonly Material $model
    ){}
    /**
     * @param Request $request
     * @return mixed
     */
    public function index(): mixed
    {
        return $this->model->getList();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        return $this->model->storeBy($request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, Request $request)
    {
        return $this->model->updateBy($id, $request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        return $this->model->where('fmaterial',$id)->delete();
    }

    /**
     * 物料修改，不存在就新增，反之修改
     * @param Request $request
     * @return mixed
     */
    public function modifyMaterial(Request $request){

        $fmaterial = $request->post('fmaterial','');

        if(empty($request->all())){
            throw new \Exception('请求数据为空');
        }

        $hasNumber = $this->model->where('fmaterial',$fmaterial)->first();

        if($hasNumber){
            return $this->model->updateBy($hasNumber->id, $request->all());
        }else{
            return $this->model->storeBy($request->all());
        }
    }
}
